/*
 * Copyright (C) 2010-2014 Enrique Lara (enrique.posix2.lara@gmail.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
 * limitations under the License.
  */
package app.transittool;

import android.content.Context;
import android.content.Intent;

import android.view.GestureDetector;

import android.view.GestureDetector.SimpleOnGestureListener;

import android.view.MotionEvent;

public class FlingLeftRightGestureListener extends SimpleOnGestureListener {
    private static final float MIN_VELOCITY = 100;
    private static final int MIN_DISTANCE = 100;
    private int idx = 0;
    private final Context context;
    private final GestureDetector detector;
    private final String actionLeft;
    private final String actionRight;

    public FlingLeftRightGestureListener(final Context context, final String actionLeft, final String actionRight) {
        super();
        this.context = context;
        detector = new GestureDetector(context, this);
        this.actionLeft = actionLeft;
        this.actionRight = actionRight;
    }

    public boolean dispatchTouchEvent(final MotionEvent e1) {
//        return this.detector.onTouchEvent(e1);
        return false; //XXX disable dispatch for now.
    }

    @Override
    public boolean onFling(final MotionEvent e1, final MotionEvent e2, final float velocityX, final float velocityY) {
        if (Math.abs(velocityX) < MIN_VELOCITY) {
            return false;
        }

        if (Math.abs(e1.getX() - e2.getX()) < MIN_DISTANCE) {
            return false;
        }

        if (e1.getX() > e2.getX()) {
            return flingLeft();
        } else {
            return flingRight();
        }
    }

    /**
     * Kick off the activity that happens when a user flings to the left.
     * <pre>
     * ==============
     * |            |
     * |  &lt;-------  |
     * |            |
     * ==============
     * </pre>
     * @return
     */
    private boolean flingLeft() {
        context.startActivity(new Intent(actionRight));

        return true;
    }

    private boolean flingRight() {
        context.startActivity(new Intent(actionLeft));

        return true;
    }
}
